package com.youth.controller.verificationCode;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("")
public class MyCodeImageController {

	private static Logger logger = Logger.getLogger(MyCodeImageController.class);

	@RequestMapping("/codeImage")
	public void codeImage1(HttpServletRequest request, HttpServletResponse response) {
		// 设置不缓存图片
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		// 指定生成的响应图片,一定不能缺少这句话,否则错误.
		response.setContentType("image/jpeg");

		AuthCodeImg aci = new AuthCodeImg().init();
		HttpSession session = request.getSession();
		session.setAttribute("imageCodeSessionKey", aci.getRandomCode().toLowerCase());
		try {
			ImageIO.write(aci.getBimg(), "JPEG", response.getOutputStream());
		} catch (IOException e) {
			logger.error(e);
		}
	}
	
	@RequestMapping("/codeImage2")
	public void codeImage2(HttpServletRequest request, HttpServletResponse response) {
		// 设置不缓存图片
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		// 指定生成的响应图片,一定不能缺少这句话,否则错误.
		response.setContentType("image/jpeg");
		
		AuthCodeImg aci = new AuthCodeImg().init();
		String verifyCode = aci.getRandomCode().toLowerCase();
		BufferedImage bi = ImageValidCode.getImage(verifyCode);

		HttpSession session = request.getSession();
		session.setAttribute("imageCodeSessionKey", verifyCode);
		try {
			ImageIO.write(bi, "JPEG", response.getOutputStream());
		} catch (IOException e) {
			logger.error(e);
		}
	}

}
